package com.ld.collegetask.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;

import com.ld.collegetask.R;
import com.ld.collegetask.chatting.ChatActivity;
import com.ld.collegetask.databinding.FragmentMessageBinding;
import com.ld.collegetask.utils.SharePreference;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.model.UserInfo;

public class MessageFragment extends BaseFragment {
    private static MessageFragment messageFragment;
    private static final String TARGET_ID = "targetId";
    private static final String GROUP_ID = "groupId";

    private View view;
    private FragmentMessageBinding binding;
    private Activity mActivity;

    private Integer userId = 0;

    private List<UserInfo> info = new ArrayList<>();

    public MessageFragment() {
    }

    public static MessageFragment getInstance() {
        if (messageFragment == null) {
            messageFragment = new MessageFragment();
        }
        return messageFragment;
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_message, container, false);
        view = binding.getRoot();
        mActivity = getActivity();

        SharePreference sp = new SharePreference(this.getContext());
        userId = sp.getUserId();

        setTitleView(mActivity, binding.ilTitle, false, true, false, false);
        setLoadingView(mActivity, binding.ilLoading);
        setTitle("消息");

        loading_go();

        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        binding.swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        binding.swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark);

        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
        binding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                info.clear();
                loading();
            }
        });

        binding.messageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                //单聊
                intent.putExtra(TARGET_ID, info.get(position).getUserName());
                intent.setClass(mActivity, ChatActivity.class);
                startActivity(intent);
//                mActivity.startActivity(new Intent(mActivity, MessageMemberInfoActivity.class));
            }
        });

        return view;
    }

    @Override
    public void loading() {
        ContactManager.getFriendList(new GetUserInfoListCallback() {
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @Override
            public void gotResult(int i, String s, final List<UserInfo> list) {
                if (i == 0) {
                    setListAdapter(list);
                    info.addAll(list);
                    loading_end();
                } else {
                    loading_error();
                }
                // 加载完数据设置为不刷新状态，将下拉进度收起来
                binding.swipeRefreshLayout.setRefreshing(false);
            }
        });
    }


    private void setListAdapter(List<UserInfo> list) {
        MessageFragment.MyListAdapter<UserInfo> adapter = null;
        adapter = new MessageFragment.MyListAdapter<>(getActivity(), list, R.layout.fragment_message_listitem, com.ld.collegetask.BR.userInfo);
        binding.setAdapter(adapter);
    }


    public class MyListAdapter<T> extends BaseAdapter {
        private Context context;//上下文环境
        private List<T> list;//通用的，不知道数据
        private int layoutId;//通用的，不知道布局
        private int variableId;//变量的id

        // 通过构造器关联数据源与数据适配器
        public MyListAdapter(Context context, List<T> list, int layoutId, int variableId) {
            this.context = context;
            this.list = list;
            this.layoutId = layoutId;
            this.variableId = variableId;
        }

        @Override
        public int getCount() {
            if (list != null)
                return list.size();
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewDataBinding viewDataBinding = null;
            if (convertView == null) {// View未被实例化，即缓冲池中无缓存才创建View
                viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(context), layoutId, parent, false);
            } else {
                viewDataBinding = DataBindingUtil.getBinding(convertView);
            }
            viewDataBinding.setVariable(variableId, list.get(position));
            return viewDataBinding.getRoot();
        }
    }
}
